<template>
    <div class="modal">
        <div class="form">
            <div class="select">
                <a-select v-model="product_id">
                    <a-option v-for="item in props.select_list" :value="item.id">{{ item.name }}</a-option>
                </a-select>
            </div>
            <a-button type="primary" @click="add_item"><template #icon><icon-plus /></template>新增</a-button>
        </div>
        <a-table :columns="columns" :data="tableData" :pagination="false">
            <template #Number="{ record }">
                <a-input-number v-model="record.number" />
            </template>
            <template #operate="{ record, rowIndex }">
                <a-button type="text" status="danger" @click="delete_item(record, rowIndex)">删除</a-button>
            </template>
        </a-table>
    </div>
</template>
<script setup>
import { ref, reactive, watch } from 'vue';
import { Message } from "@arco-design/web-vue";
const props = defineProps({
    data: Object,
    select_list: Array
});
const emit = defineEmits(["submit"]);
const columns = reactive([
    {
        title: '所需藏品',
        dataIndex: 'product.name',
        align: 'center',
        width: 300
    },
    {
        title: '所需数量',
        dataIndex: 'number',
        slotName: 'Number',
        align: 'center',
        width: 300
    },
    {
        title: '操作',
        align: 'center',
        slotName: 'operate'
    },
]);
const tableData = ref([]);
watch(() => props.data, () => {
    tableData.value = props.data;
});

const product_id = ref("");
const add_item = () => {
    if (!product_id.value) return;
    const index = tableData.value.findIndex(item => item.id == product_id.value);
    if (index > -1) {
        Message.error("已存在");
        return;
    };
    const dataItem = props.select_list.find(item => item.id == product_id.value);
    tableData.value.push({
        id: dataItem.id,
        product: {
            name: dataItem.name,
            id: dataItem.id,
        },
        number: 0
    });
};
const delete_item = (record, index) => tableData.value.splice(index, 1);
const get_data = async () => {
    let need_id = [],
        number_need = [],
        need_product_id = [];
    tableData.value.forEach(item => {
        need_id.push(item.product.id);
        need_product_id.push(item.product.id);
        number_need.push(item.number);
    });
    let formData = {
        need_id,
        number_need,
        need_product_id
    };
    emit("submit", formData);
};
defineExpose({ get_data });
</script>
<style scoped lang="less">
.modal {
    width: 100%;

    .form {
        display: flex;
        padding-bottom: 20px;

        .select {
            width: 300px;
            margin-right: 10px;
        }
    }
}
</style>